﻿using System;
using System.Collections.Generic;
using System.Data.SqlClient;
using System.Linq;
using System.Text;
using System.Globalization;

namespace RowCountDataCollector
{
    public class SQLHelper
    {
        private const string DatabaseConnectionString = "Data Source={0};Initial Catalog={1};Integrated Security=True";

        // Get the row count
        public static int GetRowCount(string server, string database, string table)
        {
            SqlConnection connection = null;
            int returnValue = 0;

            try
            {
                string connectionString = string.Format(CultureInfo.InvariantCulture, DatabaseConnectionString, server, database);
                connection = new SqlConnection(connectionString);
                connection.Open();
                returnValue = GetRowCount(connection, table);
            }
            finally
            {
                if (connection != null)
                {
                    // Close the connection if it was opened above.
                    connection.Dispose();
                }
            }

            Console.WriteLine("Retrieved a detail count of: {0}", returnValue);
            return returnValue;
        }

        // Get the row count for the given table
        private static int GetRowCount(SqlConnection connection, string table)
        {
            string selectLoadTestStatement = "select count(*) from {0}";
            string sqlstmt = string.Format(selectLoadTestStatement, table);
            SqlCommand sqlCommand = new SqlCommand(sqlstmt, connection);
            using (SqlDataReader dataReader = sqlCommand.ExecuteReader())
            {
                if (dataReader.Read())
                {
                    return dataReader.IsDBNull(0) ? 0 : dataReader.GetInt32(0);
                }
                else
                {
                    return 0;
                }
            }
        }
    }
}
